package allrobots.RobotThread;

import allrobots.Robot.RobotMessage;
import allrobots.Robot.RobotMessageMap;
import allrobots.Robot.RobotsOosAndOis;
import allrobots.Robot.RobotsSocketMap;
import allrobots.pojo.SystemSocket;
import allrobots.sendMessages.Register.Registration;
import t10086.Data.Map.TextCoordinate;
import t10086.Data.Robot.RobotInfo;
import t10086.Data.Robot.RobotType;
import t10086.Model.Messages.Message;
import t10086.Model.Messages.MessageType;

import java.awt.*;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class RobotThread implements Runnable {
    private Integer robotId;//机器人号
    private int port;  // 系统目标端口号
    private String ipAddress;  // 系统 IP 地址
    public static boolean connectionStateSystem = false;//连接状态
    private ObjectOutputStream oos;//连接的oos
    private ObjectInputStream ois;//连接的ois
    private Socket socket;//连接的socket
    private ServerSocket serverSocket;//被连接的端口
    private InetAddress inetAddress;//被连接的地址

    public RobotThread(Integer robotId) throws IOException {
        this.robotId=robotId;
        this.port = SystemSocket.port;
        this.ipAddress = SystemSocket.ipAddress;
    }

    @Override
    public void run() {
        try {
            connect();  // 连接主系统；
        } catch (IOException e) {
            return;
        }
        new Thread(new Connected(robotId,serverSocket)).start();//作为服务端，等待被发药机或者药剂师连接
        new Thread(new RegularReception(robotId)).start();//定期接收系统信息
//        new Thread(new RegularReplies(robotId)).start();//定期汇报自己的信息
        while (connectionStateSystem){
            try {
                Thread.sleep(100000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("机器人"+robotId+"还活着");
        }
    }

    private void connect() throws IOException {
        try {
            socket = new Socket(ipAddress, port);
            oos = new ObjectOutputStream(socket.getOutputStream());
            ois = new ObjectInputStream(socket.getInputStream());
            RobotsOosAndOis ros=new RobotsOosAndOis(oos,ois,socket);
            //将与系统连接的socket保存在hash表中
            RobotsSocketMap.robotsSocketMap.put(robotId,ros);
//            System.out.println(RobotsSocketMap.robotsSocketMap.size()+"          插入");
            connectionStateSystem = true;
            //机器人作为被连接时需要的端口号
            try {
                serverSocket = new ServerSocket(0);
                inetAddress = InetAddress.getLocalHost();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            RobotMessage robot1=RobotMessageMap.robotMap.get(robotId);
            robot1.setListenedSocket(new InetSocketAddress(inetAddress, serverSocket.getLocalPort()));
            RobotMessageMap.robotMap.put(robotId,robot1);
            //给系统发送注册信息
            RobotMessage robot=RobotMessageMap.robotMap.get(robotId);
            Message toRobotMessage = new Message(MessageType.REGISTER, new Registration(RobotType.ROBOT,robot.getSerialNum(),new InetSocketAddress(inetAddress.getHostAddress(),serverSocket.getLocalPort()),robot.getPosition()));
            toRobotMessage.setSender((InetSocketAddress) socket.getLocalSocketAddress());
            System.out.println("机器人注册"+robot.getSerialNum()+"地址和端口:"+socket.getLocalSocketAddress()+" "+socket.getPort());
            //接收者
            toRobotMessage.setReceiver((InetSocketAddress) socket.getRemoteSocketAddress());
//            System.out.println(socket.getRemoteSocketAddress());
            oos.writeObject(toRobotMessage);
            oos.flush();
            System.out.println("机器人"+robot.getSerialNum()+"注册成功"+"  机器人数量是:"+RobotMessageMap.robotMap.size());
            System.out.println("Robot Connect System Success");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
